package com.zhihuichongcheng.application.widget;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.AttributeSet;
import android.view.KeyEvent;
import android.view.View;
import android.widget.EditText;

import com.zhihuichongcheng.application.base.BaseActivity;
import com.zhihuichongcheng.application.bean.mine.UserBean;
import com.zhihuichongcheng.application.ui.im.activity.UserListActivity;
import com.zhihuichongcheng.application.ui.task.AtUserListActivity;
import com.zhihuichongcheng.application.util.CollectionUtils;
import com.zhihuichongcheng.application.util.StringUtils;

import java.util.ArrayList;
import java.util.List;

import static com.zhihuichongcheng.application.base.BaseActivity.EXTRA_RESPONSE_CODE_SUCCESS;

/**
 * Super EditText Created by LK on 2017/2/6.
 */
public class SuperEditText extends EditText implements BaseActivity.OnActivityGetResult {
    public static final int REQUEST_CODE_GET_USERS = 13213;
    //@人员列表
    private List<UserBean> userList = new ArrayList<>();
    private BaseActivity baseActivity;
    private int currentTaskId;

    private TextWatcher textWatcher = new TextWatcher() {
        private int currentLength = 0;

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            currentLength = null == s ? 0 : s.length();
        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
        }

        @Override
        public void afterTextChanged(Editable s) {
            if (null != s && s.toString().length() > 0 && s.toString().endsWith("@") && s.length() > currentLength && currentTaskId > 0) {
                startUserListActivity();
            }
        }
    };
    private OnKeyListener onKeyListener = new OnKeyListener() {
        @Override
        public boolean onKey(View v, int keyCode, KeyEvent event) {
            if (keyCode == KeyEvent.KEYCODE_DEL && event.getAction() == KeyEvent.ACTION_DOWN) { //当为删除键并且是按下动作时执行
                int selectionStart = getSelectionStart();
                int lastPos = 0;
                for (int i = 0; i < userList.size(); i++) { //循环遍历整个输入框的所有字符
                    String text = getText().toString();
                    String key = "@" + userList.get(i).getUserName() + " ";
                    lastPos = text.indexOf(key, lastPos);
                    if (lastPos != -1) {
                        if (selectionStart != 0 && selectionStart >= lastPos && selectionStart <= (lastPos + userList.get(i).getUserName().length() + 2)) {
                            String sss = getText().toString();
                            setText(sss.substring(0, lastPos) + sss.substring(lastPos + 2 + userList.get(i).getUserName().length())); //字符串替换，删掉符合条件的字符串
                            userList.remove(i); //删除对应实体
                            setSelection(lastPos); //设置光标位置
                            return true;
                        }
                    } else {
                        lastPos += ("@" + userList.get(i).getUserName() + " ").length();
                    }
                }
            }
            return false;
        }
    };

    public SuperEditText(Context context) {
        super(context);
    }

    public SuperEditText(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public SuperEditText(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    private void startUserListActivity() {
        Bundle bundleExecutor = new Bundle();
        bundleExecutor.putInt(AtUserListActivity.EXTRA_TASK_ID, currentTaskId);
        baseActivity.startActivityForResult(AtUserListActivity.class,
                REQUEST_CODE_GET_USERS,
                bundleExecutor);
    }

    @Override
    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
        super.onLayout(changed, left, top, right, bottom);
        this.setOnKeyListener(onKeyListener);
        Context context = getContext();
        if (context instanceof BaseActivity) {
            baseActivity = (BaseActivity) getContext();
            baseActivity.addOnGetResult(this);
            removeTextChangedListener(textWatcher);
            addTextChangedListener(textWatcher);
        }
    }

    public void removeUser(List<UserBean> users) {
        CollectionUtils.iterator(users, new CollectionUtils.AIIteratorListCallBack() {
            @Override
            public boolean callback(Object data, int position) {
                removeUser((UserBean) data);
                return false;
            }
        });
    }

    public void removeUser(UserBean userBean) {
        if (null != userBean) {
            this.userList.remove(userBean);
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == REQUEST_CODE_GET_USERS && resultCode == EXTRA_RESPONSE_CODE_SUCCESS) {
            List<UserBean> users = data.getParcelableArrayListExtra(UserListActivity.EXTRA_RESULT_USERS);
            addUser(users);
        }
    }

    public void addUser(List<UserBean> users) {
        CollectionUtils.iterator(users, new CollectionUtils.AIIteratorListCallBack() {
            @Override
            public boolean callback(Object data, int position) {
                addUser((UserBean) data);
                return false;
            }
        });
    }

    public void addUser(UserBean userBean) {
        if (null != userBean) {
            this.userList.add(userBean);
            if (!StringUtils.isEmpty(getText().toString()) && getText().toString().endsWith("@")) {
                append(userBean.getUserName() + " ");
            } else {
                append("@" + userBean.getUserName() + " ");
            }
            userList.add(userBean);
        }
    }

    public void setTaskId(int taskId) {
        this.currentTaskId = taskId;
    }

    public String getAtUserIds() {
        final String[] result = {""};
        CollectionUtils.iterator(userList, new CollectionUtils.AIIteratorListCallBack() {
            @Override
            public boolean callback(Object data, int position) {
                String userId = ((UserBean) data).getUserId();
                if (!result[0].contains(userId)) {
                    result[0] += userId + ",";
                }
                return false;
            }
        });
        return result[0];
    }
}
